package net.fornwall.eclipsecoder.arena;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.JTextField;
import javax.swing.Timer;

public class PointsUpdater extends Timer implements ActionListener {

	private static DecimalFormat decimalFormat = new DecimalFormat("####.00");

	private static final int INTERVAL = 1000;

	private static final long serialVersionUID = 3256437019256042801L;

	/**
	 * Total time allocated for solving all the problems (75 minutes).
	 */
	private static final long TT = 75 * 60 * 1000;

	private static final long TT_SQUARED = TT * TT;

	private double maxPoints;

	private JTextField pointsField;

	private long startTime;

	public PointsUpdater(JTextField pointsField) {
		super(INTERVAL, null);
		startTime = System.currentTimeMillis();
		this.pointsField = pointsField;
		addActionListener(this);
	}

	public void actionPerformed(ActionEvent e) {
		pointsField.setText(decimalFormat.format(getSubmissionScore()) + " / "
				+ maxPoints);
	}

	private double getSubmissionScore() {
		long spentTime = System.currentTimeMillis() - startTime;

		// See
		// http://www.topcoder.com/tc?module=Static&d1=help&d2=ratedEvent#score
		// for the formula below used by TopCoder to score the submission.
		return maxPoints
				* (0.3 + (0.7 * TT_SQUARED)
						/ (10 * (spentTime * spentTime) + TT_SQUARED));
	}

	public void start(double theMaxPoints) {
		this.maxPoints = theMaxPoints;
		startTime = System.currentTimeMillis();
		if (isRunning()) {
			stop();
		}
		super.start();
	}
}
